import { NextApiRequest, NextApiResponse } from 'next'
import {withIronSessionApiRoute} from 'iron-session/next'
import {prepareConnection} from 'db/index'
import { Article,Tag} from 'db/entity/index'
import {ironOptions} from 'config/index'
import { EXCEPTION_ARTICLE } from 'pages/api/config/codes'

export default withIronSessionApiRoute(update,ironOptions)

async function update(req: NextApiRequest, res: NextApiResponse) {
    const {title='',content='',id = 0,tagIds=[]} = req.body
    // 连接数据库
    const db = await prepareConnection()
    const articleRepo = db.getRepository(Article)
    const tagRepo = db.getRepository(Tag)
    const tags = await tagRepo.find({
        where: tagIds?.map((tagId:number) => ({id: tagId})),
    })
    // 操作数据库，写入数据
    const article = await articleRepo.findOne({
        where:{
            id
        },
        relations:['user']
    })
    // 判断数据是否存在
    if(article){
        article.title = title
        article.content = content
        article.update_time = new Date()
        if(tags){
            const newTags = tags?.map(tag => {
                tag.article_count = tag?.article_count + 1
                return tag
            })
            console.log(newTags,123)
            article.tags = newTags
        }
         // 保存数据
        const resArticle = await articleRepo.save(article)
        if(resArticle){
            // 返回数据
            res?.status(200).json({code:0,msg:'更新成功',data:resArticle})
        }else{
            // 返回错误
            res?.status(200).json({...EXCEPTION_ARTICLE.UPDATE_FAILED})
        }
    }else{
        res?.status(200).json({...EXCEPTION_ARTICLE.NOT_FAILED})
    }
}